package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        Date date = new Date(System.currentTimeMillis());
        //在这里完成向订单表及其附属表插入数据的操作
        //首先获取一个订单id
        String orderId = globalIdGeneratorUtil.getNextSeq("orderId", 1);
        createOrderContext.setOrderId(orderId);
        Order order = getOrderByCreateOrderContext(createOrderContext, date, orderId);
        int affectRows = orderMapper.insertSelective(order);
        if (affectRows < 1) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                    OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }
        //再插入订单商品表order-item
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto source : cartProductDtoList) {
            OrderItem target = getOrderItemByCartProductDto(orderId, source);
            //插入
            int affectRows2 = orderItemMapper.insertSelective(target);
            if (affectRows2 < 1) {
                throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                        OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
            }
        }
        return true;
    }

    private Order getOrderByCreateOrderContext(CreateOrderContext createOrderContext, Date date, String orderId) {
        //首先插入订单表order
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setCreateTime(date);
        order.setUpdateTime(date);
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getUserName());
        order.setPayment(createOrderContext.getOrderTotal());
        return order;
    }

    private OrderItem getOrderItemByCartProductDto(String orderId, CartProductDto source) {
        OrderItem target = new OrderItem();
        //生成一个订单商品id也是全局唯一的
        String orderItemId = globalIdGeneratorUtil.getNextSeq("orderItemId", 1);
        target.setId(orderItemId);
        target.setOrderId(orderId);
        target.setItemId(source.getProductId());
        target.setNum(source.getProductNum());
        target.setTitle(source.getProductName());
        target.setPrice(source.getSalePrice());
        BigDecimal totalFee = source.getSalePrice().multiply(BigDecimal.valueOf(source.getProductNum()));
        target.setTotalFee(totalFee);
        target.setPicPath(source.getProductImg());
        target.setStatus(3);
        return target;
    }

}
